package com.jugheadzhou.gateway.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author muweijun
 * @Date 2021/5/19--18:11
 **/
@Slf4j
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USER = "user";
    private static final String CLAIM_KEY_USERID = "uerid";
    private static final String CLAIM_KEY_NAME = "name";
    private static final String CLAIM_KEY_DEPTNAME = "detptname";
    private static String secret = "mz-admin-secret";

    /**
     * 从token中获取JWT中的负载
     */
    private static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("JWT格式验证失败: {}", token);
        }
        return claims;
    }

    /**
     * 从token中获取登录用户名
     */
    public static String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从token中获取登录用户部门
     */
    public static Map<String, String> getUserFromToken(String token) {
        Map<String, String> map = new HashMap<>();
        try {
            Claims claims = getClaimsFromToken(token);
            map.put("id", claims.get(CLAIM_KEY_USERID, Integer.class).toString());
            map.put("deptId", claims.get(CLAIM_KEY_USER, String.class));
            map.put("nicknames", claims.get(CLAIM_KEY_NAME, String.class));
            map.put("deptName", claims.get(CLAIM_KEY_DEPTNAME, String.class));
            map.put("doctorName",  claims.get(CLAIM_KEY_NAME, String.class));
        } catch (Exception e) {
            map = null;
        }
        return map;
    }

    public static String getDeptNameFromToken(String token) {
        String name;
        try {
            Claims claims = getClaimsFromToken(token);
            name = (String) claims.get(CLAIM_KEY_DEPTNAME);
        } catch (Exception e) {
            name = null;
        }
        return name;
    }


    /**
     * 判断token是否已经失效
     */
    public static boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        if(expiredDate.before(new Date())){
            log.error("登录过期");
            throw new RuntimeException("登录过期");
        }
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    public static Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
}
